package com.example.threadPool;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description : TODO
 * @Author : ZYX
 * @Date : 2022/6/16 15:37
 * @Version : 1.0
 **/
@Slf4j
public class MyThreadPoolExecutor extends ThreadPoolExecutor {

    private AtomicLong numTasks = new AtomicLong();
    private AtomicLong totalTime = new AtomicLong();
    private ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, MyThreadPoolExecutorConfig.MyRejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        log.info("Thread {},Runnable {}",r.toString(),r.toString());
        startTime.set(System.currentTimeMillis());
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        numTasks.incrementAndGet();
        long taskTime = System.currentTimeMillis() - startTime.get();
        totalTime.addAndGet(taskTime);
        if ( t != null ) {
            log.info("Runnable {},这次任务执行时间是{},截至目前为止总耗时是{},异常是{}", r.toString(),taskTime,totalTime.get(),t.getMessage());
        }
        log.info("Runnable {},这次任务执行时间是{},截至目前为止总耗时是{},无异常", r.toString(),taskTime,totalTime.get());
    }

    @Override
    protected void terminated() {
        log.info("terminated 线程关闭 总耗时是{},总任务数是 {},平均耗时是{}",totalTime.get(),numTasks.get(),totalTime.get()/numTasks.get());

    }

    @Override
    public void execute(Runnable command) {
        super.execute(command);
    }

}
